package com.cxl.controller;

import com.cxl.entity.User;
import com.cxl.repository.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author: 20971
 * @time: 2022/3/7 22:50
 * @description:
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserDao userDao;

    @Autowired
    MongoTemplate mongoTemplate;

    /*列表*/
    @PostMapping(value = "/list")
    public Page<User> userList(@RequestBody User user) {
     /*   //查询条件
        Date begindate = user.getBegindate();
        Date enddate = user.getEnddate();*/
        /*分页*/
        PageRequest of = PageRequest.of(user.getPageNum()-1, user.getPageSize());

        /*查询数据*/
        Query query = new Query();
//        List<User> list = userDao.findAll();
        //模糊查询条件封装
        Criteria criteria = new Criteria();
        //排序
        query.with(Sort.by(Sort.Direction.ASC, "content"));
/*
        if (null!=begindate){
            criteria =  Criteria.where("logdate").gte(begindate);
        }
        if (null!=enddate){
            criteria.andOperator(Criteria.where("logdate").lte(enddate));
        }*/
        query.addCriteria(criteria);
        //总条数
        long count = mongoTemplate.count(query,user.getClass());
        //分页
        query.with(of);
        //封装
        List<User> users = mongoTemplate.find(query, User.class);
        Page<User> all = new PageImpl<>(users, of, count);
        return all;
    }

    /*添加*/
    @PostMapping("add")
    public boolean save(@RequestBody User user){
        User save = userDao.save(user);
        if (null!=save.getId()){
            return true;
        }
        return false;
    }

    /*删除*/
    @PostMapping("del")
    public boolean del(@RequestBody User user){
        try{
            userDao.deleteById(user.getId());
        }catch (Exception e){
            return false;
        }
        return true;
    }
}
